package com.cn.web.controller.api;

import cn.com.allunion.common.AllUnionResult;
import cn.com.allunion.common.UUIDGenerator;
import cn.com.allunion.common.page.QueryResult;
import cn.com.allunion.sms.pojo.Userbase;
import cn.com.allunion.sms.pojo.UserbaseSmsbusiness;
import cn.com.allunion.sms.service.mybatis.UserbaseService;
import cn.com.allunion.sms.service.mybatis.UserbaseSmsbusinessService;
import com.cn.web.bean.PageViewResult;
import com.cn.web.bean.UserResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 管理平台用户控制器
 * Created by YangJie on 2016/4/19.
 */
@Controller
@RequestMapping("/user")
public class UserbaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserbaseController.class) ;

    @Autowired
    UserbaseService userbaseService ;

    @Autowired
    UserbaseSmsbusinessService userbaseSmsbusinessService ;

    @Value("${maxResult}")
    int pageSize ;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(@RequestParam(value = "username") String username,
                        @RequestParam(value = "password") String password, HttpSession session) {

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("username: {} , password: {}", username, password);
        }
        // 用户名和密码为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return AllUnionResult.build(HttpStatus.BAD_REQUEST.value(), "用户名和密码不能为空字符串。", null);
        }
        try {
            Userbase userbase = userbaseService.login(username, password);
            if (null != userbase) {
                session.setAttribute("user", userbase);
                return AllUnionResult.ok();
            } else {
                return AllUnionResult.build(HttpStatus.BAD_REQUEST.value(), "登录失败，用户名或密码错误。", null);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return AllUnionResult.build(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统内部错误") ;
    }

    /**
     * 用户注销
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    public Object logout(HttpSession session) {
        if (null != session.getAttribute("user")) {
            session.invalidate();
        }
        return AllUnionResult.ok();
    }

    /**
     * 新增用户
     * @param username 用户名
     * @param password 密码
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(@RequestParam(value = "username") String username,
                         @RequestParam(value = "password") String password) {
        // 用户名和密码为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return AllUnionResult.build(HttpStatus.BAD_REQUEST.value(), "用户名和密码不能为空字符串。", null);
        }

        try {
            List<Userbase> userbases = userbaseService.findByCriteria(username, null, null, null, null);
            if (CollectionUtils.isEmpty(userbases)) { // 不存在用户名
                Userbase userbase = new Userbase();
                userbase.setUserId(UUIDGenerator.generatorRandomUUID());
                userbase.setUserName(username);
                userbase.setPassWord(password);
                userbase.setUserType("admin");
                userbase.setWritepermission(true);

                boolean result = userbaseService.save(userbase);
                return result ? AllUnionResult.ok(UserResult.convert(userbase))
                        : AllUnionResult.build(HttpStatus.INTERNAL_SERVER_ERROR.value(), "新增用户失败");
            } else {
                return AllUnionResult.build(HttpStatus.BAD_REQUEST.value(), "参数用户名已经存在，更换用户名后重新添加") ;
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

        return AllUnionResult.build(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统内部错误") ;
    }

    /**
     * 编辑用户
     * @param userId 用户ID
     * @param username 用户名
     * @param password 密码
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestParam(value = "userId") String userId,
                         @RequestParam(value = "username") String username,
                         @RequestParam(value = "password") String password) {
        // 用户ID，用户名和密码为空
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return AllUnionResult.build(HttpStatus.BAD_REQUEST.value(), "用户ID、用户名和密码不能为空字符串。", null);
        }

        try {
            Userbase userbase = userbaseService.findById(userId);
            if (null != userbase) {
                userbase.setUserName(username);
                userbase.setPassWord(password);
                userbaseService.update(userbase) ;
                return AllUnionResult.ok(UserResult.convert(userbase)) ;
            }
            return AllUnionResult.build(HttpStatus.NOT_FOUND.value(), "参数用户名不存在") ;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return AllUnionResult.build(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统内部错误") ;
    }

    /**
     * 为用户设置业务
     * @param businessIds 和用户关联业务ids，使用,间隔，例如aaaa,bbb,ccc
     */
    @RequestMapping(value = "/setbusiness", method = RequestMethod.POST)
    @ResponseBody
    public Object setBusiness(@RequestParam("businessIds") String businessIds, HttpSession session) {
        if (StringUtils.isBlank(businessIds)) {
            return AllUnionResult.build(HttpStatus.BAD_REQUEST.value(), "参数业务ID集合不能为空字符串", null);
        }

        Userbase user = (Userbase) session.getAttribute("user");
        List<UserbaseSmsbusiness> usList = null ;

        if (-1 != businessIds.indexOf(",")) {
            String[] idArray = businessIds.split(",") ;
            usList = new ArrayList<>(idArray.length) ;
            UserbaseSmsbusiness us = null;
            for (String sId: idArray) {
                us = new UserbaseSmsbusiness();
                us.setUserbaseSmsbusinessId(UUIDGenerator.generatorRandomUUID());
                us.setUserId(user.getUserId());
                us.setSmsBusinessId(sId);

                usList.add(us);
            }
        } else {
            usList = new ArrayList<>(1);
            UserbaseSmsbusiness us = new UserbaseSmsbusiness() ;
            us.setUserbaseSmsbusinessId(UUIDGenerator.generatorRandomUUID());
            us.setUserId(user.getUserId());
            us.setSmsBusinessId(businessIds);
            usList.add(us);
        }

        try {
            // 要判断传递过来的业务id是否正确，如果业务id无效，那么这里的执行应该会出现错误？
            if (CollectionUtils.isNotEmpty(usList)) {
                userbaseSmsbusinessService.setBusinesses(usList) ;
            }
            return AllUnionResult.ok() ; // 设置成功
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

        return AllUnionResult.build(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统内部错误或传递业务ID集合无效") ;
    }

    /**
     * 为用户设置状态
     * @param userId 用户id
     */
    @RequestMapping(value = "/setstatus", method = RequestMethod.POST)
    @ResponseBody
    public Object setStatus(@RequestParam(value = "userId") String userId) {
        if (StringUtils.isBlank(userId)) {
            return AllUnionResult.build(HttpStatus.BAD_REQUEST.value(), "用户ID不能为空字符串");
        }

        Userbase userbase = userbaseService.findById(userId);
        if (null != userbase) {
            if (userbase.getEnabled()) {
                userbase.setEnabled(false);
            } else {
                userbase.setEnabled(true);
            }
            try {
                userbaseService.update(userbase) ;
                return AllUnionResult.ok(UserResult.convert(userbase)) ;
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            }
            return AllUnionResult.build(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统内部出现错误");
        }

        return AllUnionResult.build(HttpStatus.BAD_REQUEST.value(), "参数用户ID无效") ;
    }


    /**
     * 分页获取用户列表
     * @param pageCurrent 当前页码，从1开始
     */
    @RequestMapping(value = "/scroll/{pageCurrent}", method = RequestMethod.GET)
    @ResponseBody
    public Object scroll(@PathVariable int pageCurrent) {
        try {
            QueryResult<Userbase> queryResult = userbaseService.getScrollData(pageCurrent, pageSize);
            PageViewResult<UserResult> pageViewResult = new PageViewResult<>(pageSize, pageCurrent);
            pageViewResult.setQueryResult(UserResult.convert(queryResult));
            return AllUnionResult.ok(pageViewResult) ;
        } catch(Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return AllUnionResult.build(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统内部出现错误");
    }

}
